package handles

import (
	"car-trade-hub/cache"
	"car-trade-hub/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func CarAdd(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	car_price, _ := strconv.Atoi(c.PostForm("car_price"))

	data := models.Car{

		CarCode:  car_code,
		CarName:  car_name,
		CarPrice: car_price,
	}

	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func OrderAdd(c *gin.Context) {

	order_code := c.PostForm("order_code")
	order_tel := c.PostForm("order_tel")
	order_name := c.PostForm("order_name")
	cid, _ := strconv.Atoi(c.PostForm("cid"))

	data := models.Order{

		OrderCode: order_code,
		OrderTel:  order_tel,
		OrderName: order_name,
		Cid:       cid,
	}

	models.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func OrderList(c *gin.Context) {

	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	var order []models.Order
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	}

	var total int64
	models.DB.Model(&models.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "成功",
		"data":  order,
		"total": total,
	})
	return
}

func CarOrderList(c *gin.Context) {

	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	/*
		SELECT
		  orders.id AS OrderId,
		  cars.car_code AS CarCode,
		  cars.car_name AS CarName,
		  cars.car_price AS CarPrice,
		  orders.order_code AS OrderCode,
		  orders.order_tel AS OrderTel,
		  orders.order_name AS OrderName
		FROM
		  cars
		  LEFT JOIN orders ON cars.id = orders.cid
	*/

	var carOrder []models.CarOrderList

	redis_key := "carOrder" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("cars").
			Select(" orders.id AS OrderId",
				"cars.car_code AS CarCode",
				"cars.car_name AS CarName",
				"cars.car_price AS CarPrice",
				"orders.order_code AS OrderCode",
				"orders.order_tel AS OrderTel",
				"orders.order_name AS OrderName",
			).
			Joins("LEFT JOIN orders ON cars.id = orders.cid").
			Offset(offset).Limit(size).
			Find(&carOrder)
		jsonData, _ := json.Marshal(carOrder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &carOrder)
	}

	var total int64
	models.DB.Model(&models.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "成功",
		"data":  carOrder,
		"total": total,
	})
	return
}
